package com.chookss.home.interview;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.InterviewEntity;
import com.chookss.home.entity.InterviewExamEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class InterviewBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.tvScope)
    TextView tvScope;
    @BindView(R.id.llScope)
    LinearLayout llScope;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.rlTitle)
    RelativeLayout rlTitle;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.rcvType)
    RecyclerView rcvType;
    @BindView(R.id.rlType)
    RelativeLayout rlType;
    private MyInterviewAdapter myInterviewAdapter;
    private MyInterviewExamAdapter myInterviewExamAdapter;
    private List<InterviewEntity> interviewEntities = new ArrayList<>();
    private List<InterviewExamEntity> interviewExamEntities = new ArrayList<>();
    private String userPost = "",userName="";
    private int index = 0;//默认选择第一个
    private Drawable drawableUp, drawableDown;
    private String interviewInit="";
    private int currentPage = 1;
    private String pageSize = "10";
    private boolean isEnd = false;//是否到底
    private String postCode;
    private int type = 0; //0一级页面没有返回1是activity要返回
    private static int SOURSE=2;//选员工所用标识
    public InterviewBaseFragment() {

    }
    public InterviewBaseFragment(int type) {
        this.type = type;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_interview, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //顶部状态栏 处理
        NavigationTools.saveUseRecord(mContext,"1","06");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            statusBar.setVisibility(View.VISIBLE);
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
        rcvType.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rcvType.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myInterviewAdapter = new MyInterviewAdapter(R.layout.item_interview_type, mContext, interviewEntities);
        rcvType.setAdapter(myInterviewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        myInterviewExamAdapter = new MyInterviewExamAdapter(R.layout.item_interview, mContext, interviewExamEntities);
        recyclerView.setAdapter(myInterviewExamAdapter);
        drawableUp = getResources().getDrawable(R.drawable.arrow_up_12);
        drawableDown = getResources().getDrawable(R.drawable.arrow_down_12);
        drawableUp.setBounds(0, 0, Utils.dip2px(mContext, 9), Utils.dip2px(mContext, 5));  //此为必须写的
        drawableDown.setBounds(0, 0, Utils.dip2px(mContext, 9), Utils.dip2px(mContext, 5));  //此为必须写的
        tvScope.setCompoundDrawables(null, null, drawableDown, null);

        userPost=new ShareUtils().getString(mContext, StaticClass.POST,"");
        userName=new ShareUtils().getString(mContext, StaticClass.USER_NICKNAME,"");
        interviewInit="您是本次面试发起人,已选面试官：";

        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getInterviewExam();

                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getInterviewExam();
            }
        });
        getData();
    }
    private void getData() {
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<InterviewEntity>>>() {
        }.getType(), null, Urls.getPostList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<InterviewEntity>>() {
            @Override
            public void onSuccess(List<InterviewEntity> data) {
                if (data != null && data.size() > 0) {
                    if(smrRf==null){
                        return;
                    }
                    interviewEntities.addAll(data);
                    InterviewEntity interviewEntity = new InterviewEntity();
                    interviewEntity.setPostName("全部");
                    interviewEntity.setPostCode("");
                    interviewEntities.add(0, interviewEntity);
                    myInterviewAdapter.notifyDataSetChanged();
                    postCode=interviewEntities.get(0).getPostCode();
                    smrRf.autoRefresh();
                    tvScope.setText(interviewEntities.get(0).getPostName());
                    llScope.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }

    private void getInterviewExam() {
        Map<String, String> map = new HashMap<>();
        map.put("postCode", postCode);
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("companyCode", new ShareUtils().getString(mContext, StaticClass.COMPANYCODE, ""));
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<InterviewExamEntity>>>() {
        }.getType(), null, Urls.getInterviewExam, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<InterviewExamEntity>>() {
            @Override
            public void onSuccess(List<InterviewExamEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    interviewExamEntities.clear();
                    myInterviewExamAdapter.notifyDataSetChanged();
                }
                if(smrRf==null||llNone==null){
                    return;
                }
                if (data != null && data.size() > 0) {
                    interviewExamEntities.addAll(data);
                    myInterviewExamAdapter.notifyDataSetChanged();
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (interviewExamEntities.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    class MyInterviewExamAdapter extends BaseQuickAdapter<InterviewExamEntity, BaseViewHolderEx> {
        private Context context;

        public MyInterviewExamAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<InterviewExamEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, InterviewExamEntity item) {

            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvAllScore = helper.getView(R.id.tvAllScore);
            TextView tvAnswerTime = helper.getView(R.id.tvAnswerTime);
            TextView tvCreate = helper.getView(R.id.tvCreate);
            TextView tvNum = helper.getView(R.id.tvNum);
            LinearLayout llRecord = helper.getView(R.id.llRecord);
            LinearLayout llPaper = helper.getView(R.id.llPaper);
            tvTitle.setText(item.getExamName());
            tvAllScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.getScore()));
            tvAnswerTime.setText("本答卷答题时长："+item.getExamTimeLength()+"分钟");
            tvCreate.setText(item.getCreateTime()+" 由"+item.getCreateEmployeeName()+"创建");
            tvNum.setText(item.getSubjectNum());
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyApp.contactEntityLogList.clear();
                    Intent intent = new Intent(mContext, ContactsLogChoiceActivity.class);
                    intent.putExtra("examCode", item.getExamCode());
                    intent.putExtra("examName", item.getExamName());
                    intent.putExtra("qrCodeValid", item.getQrCodeValid());
                    intent.putExtra("hrName", interviewInit);
                    intent.putExtra("source", SOURSE+"");
                    mContext.startActivity(intent);
                }
            });
            llPaper.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyApp.contactEntityLogList.clear();
                    Intent intent = new Intent(mContext, ContactsLogChoiceActivity.class);
                    intent.putExtra("examCode", item.getExamCode());
                    intent.putExtra("examName", item.getExamName());
                    intent.putExtra("qrCodeValid", item.getQrCodeValid());
                    intent.putExtra("hrName", interviewInit);
                    intent.putExtra("source", SOURSE+"");
                    mContext.startActivity(intent);
                }
            });
            llRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, InterviewRecordsActivity.class);
                    intent.putExtra("examCode", item.getExamCode());
                    intent.putExtra("type", 1);
                    mContext.startActivity(intent);
                }
            });
        }
    }

    class MyInterviewAdapter extends BaseQuickAdapter<InterviewEntity, BaseViewHolderEx> {
        private Context context;

        public MyInterviewAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<InterviewEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, InterviewEntity item) {

            TextView tvTile = helper.getView(R.id.tvTile);
            ImageView ivChoice = helper.getView(R.id.ivChoice);
            if (index == helper.getItemPosition()) {
                ivChoice.setVisibility(View.VISIBLE);
            } else {
                ivChoice.setVisibility(View.GONE);
            }
            tvTile.setText(item.getPostName());
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    index = helper.getItemPosition();
                    myInterviewAdapter.notifyDataSetChanged();
                    rlType.setVisibility(View.GONE);
                    tvScope.setCompoundDrawables(null, null, drawableDown, null);
                    postCode=item.getPostCode();
                    smrRf.autoRefresh();
                    tvScope.setText(item.getPostName());
                    llScope.setVisibility(View.VISIBLE);
                }
            });
        }
    }
    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }
    @OnClick({R.id.title_back,R.id.llScope, R.id.rlType, R.id.icon_msjl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                if(mContext!=null){
                    mContext.finish();
                }
                break;
            case R.id.llScope:
                if(rlType==null){
                    return;
                }
                if (rlType.getVisibility() == View.VISIBLE) {
                    rlType.setVisibility(View.GONE);
                    tvScope.setCompoundDrawables(null, null, drawableDown, null);
                } else {
                    if (interviewEntities.size() > 0) {
                        tvScope.setCompoundDrawables(null, null, drawableUp, null);
                        rlType.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case R.id.rlType:
                if(rlType==null){
                    return;
                }
                rlType.setVisibility(View.GONE);
                break;
            case R.id.icon_msjl:

                mContext.startActivity(new Intent(mContext, InterviewRecordsActivity.class));
                break;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
